//
//  LoginPageViewController.m
//  GolfFriend
//
//  Created by vescky on 13-11-24.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "LoginPageViewController.h"
#import "AppsEngine.h"
#import "SVProgressHUD.h"
#import "AppsLocationManager.h"
#import "UserSession.h"
#import "GFVOParser.h"
#import "GFVOs.h"
#import "AppDelegate.h"
//#import "RegisterAgreementViewController.h"
#import "WebappBrowserViewController.h"
#import "LoginPageLevel2ViewController.h"

@interface LoginPageViewController () {
}

@end

@implementation LoginPageViewController

#pragma mark - lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    if (ios7OrLater) {
        [self.view setFrame:CGRectMake(self.view.frame.origin.x, 20, self.view.frame.size.width, self.view.frame.size.height)];
    }
    
    [lgScrollView setContentSize:CGSizeMake(lgScrollView.frame.size.width, self.view.frame.size.height + 20)];
    btnCheckBox.selected = YES;
    
    //监听键盘高度的变换
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    // 键盘高度变化通知，ios5.0新增的
#ifdef __IPHONE_5_0
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 5.0) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
#endif
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private
- (IBAction)getSMSCode:(id)sender {
    if (!tfPhone.text || tfPhone.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"手机号码不能为空"];
        return;
    }
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:tfPhone.text,@"phone", nil];
    [[AppsEngine shareAppsEngine] submitRequest:@"gfGetSMSAuthCode" param:dict onCompletion:^(id jsonResponse) {
        NSLog(@"%@",jsonResponse);
        NSDictionary *rDict = jsonResponse;
        if ([rDict objectForKey:@"status"] && [[rDict objectForKey:@"status"] isEqualToString:@"fail"]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"获取短信验证码失败，请确认您输入的号码是否正确。如有疑问，请来电咨询我们。" delegate:self cancelButtonTitle:@"咨询" otherButtonTitles:@"关闭", nil];
            [alert show];
        }
        else {
            [SVProgressHUD showSuccessWithStatus:@"验证码发送成功，请注意检查手机!"];
        }
    } onError:^(NSError *error) {
        NSLog(@"%@",error);
    } method:@"GET"];
    
}


#pragma mark - Responding to keyboard events
- (void)keyboardWillShow:(NSNotification *)notification {
    if (!iPhone5) {
        [lgScrollView setContentOffset:CGPointMake(0, 80) animated:YES];
    }
}



- (void)keyboardWillHide:(NSNotification *)notification {
    [lgScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (IBAction)btnAction:(id)sender {
    UIButton *btn = (UIButton*)sender;
    if (btn.tag == 101) {
        //勾选
        btnCheckBox.selected = !btnCheckBox.selected;
    }
    else if (btn.tag == 102) {
        //跳转
        WebappBrowserViewController *gVc = [[WebappBrowserViewController alloc] init];
        gVc.title = @"用户注册与隐私协议";
        gVc.webappLink = @"http://mingyuanhui.sinaapp.com/test/webveiw/agreement.html";
        [self.navigationController pushViewController:gVc animated:YES];
        [self.navigationController setNavigationBarHidden:NO];
    }
}


- (IBAction)btnLogin:(id)sender {
    if (!tfPhone.text || tfPhone.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"手机号码不能为空"];
        return;
    }
    if (!tfSMSCode.text || tfSMSCode.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"短信验证码不能为空"];
        return;
    }
    NSLog(@"login,%@",[[AppsLocationManager sharedManager] currentLocation]);
    CLLocation *currentLocation = [[AppsLocationManager sharedManager] currentLocation];

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:tfPhone.text,@"phone",
                                 tfSMSCode.text,@"smsAuthCode",
                                 GetToken_Alias,@"token",
                                 [NSString stringWithFormat:@"%f",currentLocation.coordinate.latitude],@"latitude",
                                 [NSString stringWithFormat:@"%f",currentLocation.coordinate.longitude],@"longitude",nil];
    
    [SVProgressHUD showWithStatus:@"正在登陆"];
    [[AppsEngine shareAppsEngine] submitRequest:@"gfUserLogin" param:dict onCompletion:^(id jsonResponse) {
        NSLog(@"%@",jsonResponse);
        [SVProgressHUD dismiss];
        NSDictionary *rDict = jsonResponse;
        if ([rDict objectForKey:@"status"] && [[rDict objectForKey:@"status"] isEqualToString:@"success"]) {
            [self handleLoginResult:rDict];
            //登陆成功
            if ([[rDict objectForKey:@"isNewUser"] integerValue]) {
                //新用户
                LoginPageLevel2ViewController *l2Vc = [[LoginPageLevel2ViewController alloc] init];
                [self.navigationController pushViewController:l2Vc animated:YES];
            }
            else {
                [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
        }
        else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您输入的验证码有误。如果多次登陆不上，请来电咨询我们。" delegate:self cancelButtonTitle:@"咨询" otherButtonTitles:@"关闭", nil];
            [alert show];
            
        }
    } onError:^(NSError *error) {
        [SVProgressHUD dismiss];
        NSLog(@"%@",error);
    } method:@"GET"];
}

- (void)handleLoginResult:(NSDictionary*)rDict {
    //保存验证码，保证私人信息，保存公开信息
    UserSession *us = [UserSession shareUserSession];
    [us saveSmsCode:tfSMSCode.text];
    NSDictionary *prDict = [[[GFVOParser shareParser] parseDataForUserPrivateInfo:rDict] toDictionary];
    NSDictionary *pbDict = [[[GFVOParser shareParser] parseDataForUserPublicInfo:rDict] toDictionary];
    [us saveUserInfo:prDict];
    [us savePublicInfo:pbDict];
    [APP_DELEGATE refreshContactBook];
    [APP_DELEGATE getMessagesFromServerOnBackground];
}

@end
